<?php
class messageSearch {

    /**
     * 搜索
     * @param $search 搜索的内容
     * @param int $start 0
     * @param int $limit 10
     * @internal param $params
     */
    public function searchMessage($search=null, $start=0, $limit=10){
        $cid = Session::$user['customerId'];
        $userId =  Session::$user['userId'];

        $messageSearch = M("message_search");
        Session::switchCustomer(0);
        Session::switchCustomer($cid);
        if($search){
            is_numeric($search)?$where['a.serialNumber']=array("like","%$search%"):$where['a.title']=array("like","%$search%");
        }
        $where['a.deleted'] = array("eq",0);
        $where['m.module'] ="messageSearch";
        $where['m.deleted'] = 0;
        $where['m.type'] = array(array("eq","text"),array("eq","image"),'or');
        $result = $messageSearch->alias('a')
            ->join("wx_".$cid."_material as m on m.moduleId=a.id")
            ->field("a.id,a.serialNumber,a.title,a.deleted,a.readCount")
            ->where($where)
            ->limit($start,$limit)
            ->group("a.id")
            ->order("a.readCount desc,a.updateTime desc")
            ->select();
        foreach ($result as $key => $item)
        {
            $result[$key]['data'] = self::getSearchInfo($item['id']);
        }
        $count = $messageSearch->alias('a')->join("wx_".$cid."_material as m on m.moduleId=a.id")
            ->where($where)->group("a.id")->select();
        //添加搜索记录
        if($search)
        {
            self::addSearchHistory($userId,$search);
        }
        Output::instance()->objArray($result,count($count));
    }

    /**
     * 获取详情
     * @param $id
     */
    public function messageInfo($id)
    {
        $userId =  Session::$user['userId'];
        self::addVisitHistory($userId,$id);
        R('MessageSearch/getMessageInfo',array($id));

    }

    /**
     * 新增浏览记录
     * @param $userId
     * @param $messageId
     * @return bool
     */
    public function addVisitHistory($userId,$messageId)
    {
        $cid = Session::$user['customerId'];
        $MessageSearch = M("message_search");
        Session::switchCustomer(0);
        $Visithistory = M("message_visit_history");
        Session::switchCustomer($cid);
        $data=[
            'cid'=>$cid,
            'userId'=>$userId,
            'messageId'=>$messageId,
            'createTime'=>date('Y-m-d H:i:s',time())
        ];
        $Visithistory->add($data);
        return $MessageSearch->where(['id'=>$messageId])->setInc('readCount',1);
    }
    /**
     * 创建搜索记录
     * @param $userId 用户userId
     * @param $content 搜索内容
     * @return mixed
     */
    public function addSearchHistory($userId,$content)
    {
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $SearchHory = M("message_search_history");
        Session::switchCustomer($cid);
        $data=[
            'cid'=>$cid,
            'userId'=>$userId,
            'content'=>$content,
            'createTime'=>date('Y-m-d H:i:s',time())
        ];
        return $SearchHory->add($data);

    }

    /**
     * 获取搜索素材详情
     * @param $id
     * @return array
     */
    public function getSearchInfo($id)
    {
        $cid = Session::$user['customerId'];

        $Material = M("material");

        $where['moduleId'] = $id;
        $where['deleted'] = 0;
        $where['module'] = "messageSearch";
        $where['type'] = array("eq","image");
        $data = $Material->where($where)
                ->limit(0,3)
                ->select();

        return self::analysisXml($data);

    }

    /**
     * 解析xml
     * @param $list
     * @return array
     */
    public function analysisXml($list){
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $productModel = M("module_product");
        $contentModel = M("micontent");
        Session::switchCustomer($cid);
        $materialModel = M("material");
        $result = [];
        foreach($list as $key=>$value){
            $data=[];
            $data['id'] = $value['id'];
            $data['updateTime'] = $value['updateTime'];
            $data['type'] = $value['type'];
            $xml = simplexml_load_string($value['xml'],'SimpleXMLElement', LIBXML_NOCDATA);
            $content = $xml->message->item;
            switch($value['type']){
                case "text":
                    $str = (String)$content->content;
                    if($str == base64_encode(base64_decode($str))){
                        $str = base64_decode($str);
                    }
                    $data['content']=$str;
                    break;
                case "news":
                    $newsId = (String)$content->newsId;
                    $data["newsid"]=$newsId;
                    $data['xml']=$materialModel->where("id=$newsId")->getField("xml");
                    break;
                case "product":
                    $materialId = (String)$content->materialId;
                    $data['materialid'] = $materialId;
                    $data['typeName'] = '商品';
                    $data['name']=$productModel->where("id=$materialId")->getField("name");
                    break;
                case "content":
                    $materialId = (String)$content->materialId;
                    $data['materialid'] = $materialId;
                    $data['typeName'] = "文章";
                    $data['name']=$contentModel->where("id=$materialId")->getField("title");
                    break;
                case "image":
                    $data['imageUrl'] = (String)$content->imageUrl;
                    break;
                case "audio":
                    $data['audioUrl'] = (String)$content->audioUrl;
                    break;
                case "video":
                    $data['videoUrl'] = (String)$content->videoUrl;
                    break;
                case "music":
                    $data['musicUrl'] = (String)$content->musicUrl;
                    $data['imageUrl'] = (String)$content->imgUrl;
                    break;
            }
            $result[]=$data;
        }
        return $result;
    }


}